package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @version 1.0
 * @description <p>管理员用户信息 业务实现</p>
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public HashMap<String, Object> loginCheck(HashMap<String, String> map) {
        String name = map.get("name");
        String password = map.get("password");
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            throw new LeadNewsException("账号或者密码不存在");
        }
        AdUser user = query().eq("name", name).one();
        if (StringUtils.isEmpty(user)) {
            throw new LeadNewsException("账号或者密码错误");
        }

//        String pwd = user.getPassword();
        String salt = user.getSalt();
        password += salt;
//        251b57454f0c600aa20a51ab03756845
        String digest = DigestUtils.md5DigestAsHex(password.getBytes());
//        每次进行加盐后校验
        if (!user.getPassword().equals(digest)) {
            throw new LeadNewsException("账号或者密码不存在");
        }
        user.setSalt("0");
        user.setPassword("0");
//        上面都是正确的话
        String token = AppJwtUtil.createToken(user.getId().longValue());
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("token", token);
        hashMap.put("user", user);

        return hashMap;
    }
}
